package com.wxzhou.wangzhuan.api;

import com.wxzhou.wangzhuan.dto.AdPreReportResponse;
import com.wxzhou.wangzhuan.dto.ResponseDto;
import com.wxzhou.wangzhuan.dto.UserInfoDto;
import com.wxzhou.wangzhuan.dto.reader.ReaderCallBack;
import com.wxzhou.wangzhuan.dto.reader.ReaderRequestInfo;
import com.wxzhou.wangzhuan.exception.AdReaderException;
import com.wxzhou.wangzhuan.security.UserContext;
import com.wxzhou.wangzhuan.service.AdService;
import io.smallrye.mutiny.Uni;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;

import java.util.Map;
import java.util.Optional;

/**
 * 阅读接口
 */
@Path("/api")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ReadApi {

    private static final Logger LOG = Logger.getLogger(ReadApi.class);

    @Inject
    AdService adService;

    @Inject
    UserContext userContext;

    /**
     * 阅读回调
     * 每次回调
     *
     * @param readerCallBack
     * @return
     */
    @POST
    @Path("/yuedu/callback")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> callback(@Valid ReaderCallBack readerCallBack) {

        return adService.readerCallBack(readerCallBack).onItem().transform(response -> {
            if (response != null) {
                return Response.ok(response).build();
            } else {
                ResponseDto<Map<String, Object>> resp = ResponseDto.fail("拉取频率过快，等会再拉取");
                return Response.status(500).entity(resp).build();
            }
        }).onFailure().recoverWithUni(throwable -> {
            String msg = "";
            if (throwable instanceof AdReaderException) {
                msg = throwable.getMessage();
                LOG.errorf("阅读回调处理失败: " + throwable.getMessage());
            } else {
                LOG.errorf(throwable, "阅读回调处理失败: " + throwable.getMessage());
            }
            ResponseDto<Map<String, Object>> resp = ResponseDto.error("阅读回调处理失败: " + msg);
            return Uni.createFrom().item(Response.status(500).entity(resp).build());
        });
    }

    /**
     * 预请求广告，表明要拉广告之前的请求
     *
     * @param readerRequestInfo
     * @return
     */
    @POST
    @Path("/reader/geturl")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> geturl(@Valid ReaderRequestInfo readerRequestInfo) {

        Optional<UserInfoDto> currentUserInfo = userContext.getCurrentUserInfo();

        return adService.getReaderInfo(readerRequestInfo, currentUserInfo).onItem().transform(response -> {
            if (response != null) {
                ResponseDto<AdPreReportResponse> resp = ResponseDto.success(response);
                return Response.ok(resp).build();
            } else {
                ResponseDto<Map<String, Object>> resp = ResponseDto.fail("拉取频率过快，等会再拉取");
                return Response.status(500).entity(resp).build();
            }
        }).onFailure().recoverWithUni(throwable -> {
            String msg = "";
            if (throwable instanceof AdReaderException) {
                msg = throwable.getMessage();
                LOG.errorf("阅读预拉失败: " + throwable.getMessage());
            } else {
                LOG.errorf(throwable, "阅读预拉失败: " + throwable.getMessage());
            }
            ResponseDto<Map<String, Object>> resp = ResponseDto.error("预拉失败: " + msg);
            return Uni.createFrom().item(Response.status(500).entity(resp).build());
        });
    }

}
